package com.gylang.commons.util;



import com.gylang.commons.enmus.BaseSortEnum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 排序工具类
 *
 * @author gylang,
 * date 2020/4/21,
 * @version 1.0
 */
public class SortUtils {

    /**
     * 将排序关键字转成排序sql 字符串
     *
     * @param baseSortEnums 排序enum
     * @param sortKeys      排序关键字
     * @return 检验后的排序sql语句片段
     */
    public static String checkSortStrList(BaseSortEnum[] baseSortEnums, List<String> sortKeys) {

        Map<String, String> checkSortMap = sortStr2SortMap(baseSortEnums, sortKeys);
        StringBuilder sortSql = new StringBuilder();
        Set<Map.Entry<String, String>> entries = checkSortMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            sortSql.append(entry.getKey())
                    .append(" ")
                    .append(entry.getValue())
                    .append(",");
        }
        //去除最后的逗号
        sortSql.deleteCharAt(sortSql.lastIndexOf(","));
        return sortSql.toString();
    }


    /**
     * 检验并前端传递的排序转成Map
     *
     * @param baseSortEnums 排序enum
     * @param sortKeys      排序key
     * @return 排序Map
     */
    private static Map<String, String> sortStr2SortMap(BaseSortEnum[] baseSortEnums, List<String> sortKeys) {

        //将排序关键字转成map, 格式 0-ASC 1-DESC
        Map<String, String> sortMap = new HashMap<>(4);
        for (String sortKey : sortKeys) {
            String[] split = sortKey.split("-");
            if (split.length == 1) {
                sortMap.put(split[0], "ASC");
            } else if (checkSortKey(split)) {
                sortMap.put(split[0], split[1]);
            }
        }
        // 检验前端参数
        //排序关键字map 用于检验
        Map<String, String> compareMap = getSortMap(baseSortEnums);
        //检验后最终用于排序的key
        Map<String, String> checkedSortMap = new HashMap<>(4);
        for (String sortKey : sortMap.keySet()) {
            if (compareMap.containsKey(sortKey)) {
                checkedSortMap.put(compareMap.get(sortKey), sortMap.get(sortKey));
            }
        }
        return checkedSortMap;

    }

    /**
     * 排序枚举转成map
     *
     * @param baseSortEnums 排序枚举
     * @return 排序枚举map
     */
    private static Map<String, String> getSortMap(BaseSortEnum[] baseSortEnums) {

        Map<String, String> sortMap = new HashMap<>(4);
        for (BaseSortEnum baseSortEnum : baseSortEnums) {
            sortMap.put(baseSortEnum.orderKey(), baseSortEnum.orderVal());
        }
        return sortMap;
    }

    private static boolean checkSortKey(String[] sortKey) {
        return sortKey.length == 2
                && ("ASC".equals(sortKey[1]) || "DESC".equals(sortKey[1]));

    }

}
